package cn.itlight.order.service.impl;

import cn.itlight.order.domain.OrderPetAcquisition;
import cn.itlight.order.dto.OrderConfirmDto;
import cn.itlight.order.mapper.OrderPetAcquisitionMapper;
import cn.itlight.order.service.IOrderPetAcquisitionService;
import cn.itlight.basic.service.impl.BaseServiceImpl;
import cn.itlight.pet.domain.Pet;
import cn.itlight.pet.domain.SearchMasterMsg;
import cn.itlight.pet.mapper.PetMapper;
import cn.itlight.pet.mapper.SearchMasterMsgMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tomliu
 * @since 2022-07-19
 */
@Service
public class OrderPetAcquisitionServiceImpl extends BaseServiceImpl<OrderPetAcquisition> implements IOrderPetAcquisitionService {


    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private PetMapper petMapper;

    @Override
    public void confirm(OrderConfirmDto orderConfirmDto) {

        // 收购成功，根据订单Id查询订单，修改订单状态为已完成，修改价格
        OrderPetAcquisition orderPetAcquisition = orderPetAcquisitionMapper.loadById(orderConfirmDto.getId());
        orderPetAcquisition.setState(1);
        orderPetAcquisition.setPrice(orderConfirmDto.getMoney());
        orderPetAcquisition.setPaytype(orderConfirmDto.getPayType());
        orderPetAcquisitionMapper.update(orderPetAcquisition);
        // 修改寻主状态为已完成
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(orderPetAcquisition.getSearchMasterMsgId());
        searchMasterMsg.setState(2);
        searchMasterMsgMapper.update(searchMasterMsg);
        // 完善宠物信息
        Pet pet = petMapper.loadById(orderPetAcquisition.getPetId());
        pet.setCostprice(orderConfirmDto.getMoney());
        petMapper.update(pet);
    }

    @Override
    public void cancelOrder(Long id) {
        // 将订单修改为拒绝
        OrderPetAcquisition orderPetAcquisition = orderPetAcquisitionMapper.loadById(id);
        orderPetAcquisition.setState(-1);
        orderPetAcquisitionMapper.update(orderPetAcquisition);
        // 2.将寻主消息的shopId置空，设置状态为已审核，归还到寻主池
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(orderPetAcquisition.getSearchMasterMsgId());
        searchMasterMsg.setShopId(null);
        searchMasterMsgMapper.update(searchMasterMsg);
        // 删除新增宠物
        petMapper.remove(orderPetAcquisition.getPetId());
    }
}
